<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { getAppVoById, deployApp, deleteApp } from '@/api/appController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { 
  ArrowLeftOutlined, 
  EditOutlined, 
  RocketOutlined, 
  PlayCircleOutlined,
  EyeOutlined,
  CalendarOutlined,
  UserOutlined,
  TagOutlined,
  GlobalOutlined,
  DeleteOutlined,
  KeyOutlined,
  CopyOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getCodeGenTypeName } from '@/constants/codeGenType'
import { getDeployUrl, getStaticPreviewUrl } from '@/config/env'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

/**
 * 安全地处理ID，始终保持为字符串类型
 */
const safeGetId = (id: string | number | undefined): string => {
  if (!id) return ''
  
  const idString = String(id)
  console.log(`ID处理: ${id} -> ${idString} (type: ${typeof id} -> string)`)
  
  return idString
}

// 应用详情数据
const app = ref<API.AppVO>({})
const loading = ref(false)
const deployLoading = ref(false)

/**
 * 获取应用详情
 */
const fetchAppDetail = async (retryCount = 0) => {
  const appId = route.params.id as string
  console.log('获取应用详情, appId:', appId, '重试次数:', retryCount)
  if (!appId) {
    console.error('应用ID不存在')
    message.error('应用ID不存在')
    router.push('/')
    return
  }

  // 只在第一次请求时显示loading
  if (retryCount === 0) {
    loading.value = true
  }

  try {
    const appIdString = safeGetId(appId)
    
    if (!appIdString) {
      console.error('应用ID为空:', appId)
      message.error('应用ID不存在')
      loading.value = false
      return
    }
    
    const res = await getAppVoById({ id: appIdString })
    console.log('应用详情响应:', res)
    
    if (res.data.code === 0 && res.data.data) {
      app.value = res.data.data
      console.log('应用详情加载成功:', app.value)
      loading.value = false
      return
    } else {
      // 如果是数据不存在且重试次数少于5次，则等待后重试
      if (res.data.message?.includes('请求数据不存在') && retryCount < 5) {
        console.log(`应用详情数据暂未同步，正在重试... (${retryCount + 1}/5)`)
        setTimeout(() => {
          fetchAppDetail(retryCount + 1)
        }, 2000)
        return
      }
      
      loading.value = false
      message.error('应用不存在或已被删除')
      router.push('/')
    }
  } catch (error) {
    // 网络错误也进行重试
    if (retryCount < 5) {
      console.log(`网络请求失败，正在重试... (${retryCount + 1}/5)`)
      setTimeout(() => {
        fetchAppDetail(retryCount + 1)
      }, 2000)
      return
    }
    
    loading.value = false
    message.error('网络连接失败，请检查网络')
    router.push('/')
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

/**
 * 编辑应用
 */
const editApp = () => {
  router.push(`/app/edit/${app.value.id}`)
}

/**
 * 进入对话页面 - 查看模式
 */
const enterChat = () => {
  router.push(`/app/chat/${app.value.id}?view=1`)
}

/**
 * 部署应用
 */
const handleDeploy = async () => {
  if (!app.value.id) return

  deployLoading.value = true
  try {
    const res = await deployApp({ appId: app.value.id })
    if (res.data.code === 0 && res.data.data) {
      const deployUrl = res.data.data
      message.success('部署成功！')
      message.info(`部署地址：${deployUrl}`, 10)
      
      // 刷新应用信息
      fetchAppDetail()
    } else {
      message.error('部署失败：' + res.data.message)
    }
  } catch (error) {
    message.error('部署失败，请检查网络连接')
  } finally {
    deployLoading.value = false
  }
}

/**
 * 预览应用
 */
const previewApp = () => {
  if (!app.value.id || !app.value.codeGenType) return
  
  const previewUrl = getStaticPreviewUrl(app.value.codeGenType, app.value.id)
  window.open(previewUrl, '_blank')
}

/**
 * 查看作品
 */
const viewWork = () => {
  if (!app.value.deployKey) {
    message.error('该应用尚未部署')
    return
  }
  
  const deployUrl = getDeployUrl(app.value.deployKey)
  window.open(deployUrl, '_blank')
}

/**
 * 复制部署密钥
 */
const copyDeployKey = async () => {
  if (!app.value.deployKey) return
  
  try {
    await navigator.clipboard.writeText(app.value.deployKey)
    message.success('部署密钥已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败，请手动复制')
  }
}

/**
 * 删除应用
 */
const handleDeleteApp = async () => {
  if (!app.value.id) {
    message.error('应用ID不存在')
    return
  }

  // 显示确认对话框
  const confirmed = await new Promise((resolve) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除应用"${app.value.appName}"吗？此操作不可撤销。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => resolve(true),
      onCancel: () => resolve(false),
    })
  })

  if (!confirmed) return

  try {
    const res = await deleteApp({ id: app.value.id })
    
    if (res.data.code === 0) {
      message.success('应用删除成功')
      // 删除成功后返回首页
      router.push('/')
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除应用失败:', error)
    message.error('删除失败，请稍后重试')
  }
}

/**
 * 检查是否可以编辑
 */
const canEdit = () => {
  return loginUserStore.loginUser.userRole === 'admin' || 
         app.value.userId === loginUserStore.loginUser.id
}

/**
 * 根据生成类型获取对应的颜色
 */
const getTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    html: 'orange',
    multi_file: 'blue',
  }
  return colorMap[type?.toLowerCase() || ''] || 'default'
}

// 页面加载时获取应用详情
onMounted(() => {
  fetchAppDetail()
})
</script>

<template>
  <div class="app-detail-page">
    <a-card class="detail-card" :loading="loading">
      <!-- 页面头部 -->
      <template #title>
        <div class="page-header">
          <a-button type="text" @click="goBack" class="back-button">
            <template #icon><ArrowLeftOutlined /></template>
            返回
          </a-button>
          <span class="page-title">应用详情</span>
        </div>
      </template>

      <template #extra>
        <a-space>
          <a-button @click="previewApp" :disabled="!app.id">
            <template #icon><EyeOutlined /></template>
            预览
          </a-button>
          
          <a-button type="primary" @click="enterChat" :disabled="!app.id">
            <template #icon><PlayCircleOutlined /></template>
            使用应用
          </a-button>

          <a-button 
            v-if="canEdit()" 
            @click="editApp"
            :disabled="!app.id"
          >
            <template #icon><EditOutlined /></template>
            编辑
          </a-button>

          <a-button 
            type="primary"
            :loading="deployLoading"
            @click="handleDeploy"
            :disabled="!app.id"
          >
            <template #icon><RocketOutlined /></template>
            部署
          </a-button>

          <a-button 
            v-if="canEdit()" 
            danger
            @click="handleDeleteApp"
            :disabled="!app.id"
          >
            <template #icon><DeleteOutlined /></template>
            删除应用
          </a-button>
        </a-space>
      </template>

      <!-- 应用信息 -->
      <div v-if="app.id" class="app-info">
        <!-- 应用基本信息 -->
        <div class="basic-info">
          <div class="app-cover">
            <img 
              v-if="app.cover" 
              :src="app.cover" 
              :alt="app.appName"
              class="cover-image"
            />
            <div v-else class="default-cover">
              <PlayCircleOutlined class="cover-icon" />
            </div>
          </div>

          <div class="app-meta">
            <h1 class="app-title">{{ app.appName || '未命名应用' }}</h1>
            
            <div class="meta-tags">
              <a-tag :color="getTypeColor(app.codeGenType)" class="type-tag">
                <template #icon><TagOutlined /></template>
                {{ getCodeGenTypeName(app.codeGenType || '') }}
              </a-tag>

              <a-tag v-if="app.priority === 99" color="gold" class="featured-tag">
                <template #icon><GlobalOutlined /></template>
                精选应用
              </a-tag>

              <a-tag v-if="app.deployKey" color="green" class="deploy-tag">
                <template #icon><RocketOutlined /></template>
                已部署
              </a-tag>
            </div>

            <!-- 创建者信息 -->
            <div class="creator-info">
              <a-avatar :src="app.user?.userAvatar" :size="32">
                <template #icon><UserOutlined /></template>
              </a-avatar>
              <div class="creator-details">
                <div class="creator-name">{{ app.user?.userName || '未知用户' }}</div>
                <div class="creator-time">
                  <CalendarOutlined />
                  创建于 {{ app.createTime ? dayjs(app.createTime).format('YYYY年MM月DD日') : '-' }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 应用详细信息 -->
        <a-divider>详细信息</a-divider>

        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="应用ID">
            {{ app.id }}
          </a-descriptions-item>
          
          <a-descriptions-item label="生成类型">
            <a-tag :color="getTypeColor(app.codeGenType)">
              {{ getCodeGenTypeName(app.codeGenType || '') }}
            </a-tag>
          </a-descriptions-item>

          <a-descriptions-item label="优先级">
            <span v-if="app.priority === 99">
              <a-tag color="gold">精选应用</a-tag>
            </span>
            <span v-else>{{ app.priority || 0 }}</span>
          </a-descriptions-item>

          <a-descriptions-item label="部署状态">
            <a-tag v-if="app.deployKey" color="green">
              已部署
            </a-tag>
            <a-tag v-else color="default">
              未部署
            </a-tag>
          </a-descriptions-item>

          <a-descriptions-item label="部署时间" v-if="app.deployedTime">
            {{ dayjs(app.deployedTime).format('YYYY-MM-DD HH:mm:ss') }}
          </a-descriptions-item>

          <a-descriptions-item label="创建时间">
            {{ app.createTime ? dayjs(app.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </a-descriptions-item>

          <a-descriptions-item label="更新时间">
            {{ app.updateTime ? dayjs(app.updateTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </a-descriptions-item>

          <a-descriptions-item v-if="app.deployKey" label="部署密钥" :span="2">
            <div style="display: flex; align-items: center; gap: 8px;">
              <KeyOutlined style="color: #1890ff;" />
              <a-input 
                :value="app.deployKey" 
                readonly 
                style="font-family: 'Monaco', 'Consolas', monospace; flex: 1;"
              >
                <template #suffix>
                  <a-tooltip title="复制密钥">
                    <a-button 
                      type="text" 
                      size="small"
                      @click="copyDeployKey"
                    >
                      <template #icon><CopyOutlined /></template>
                    </a-button>
                  </a-tooltip>
                </template>
              </a-input>
            </div>
          </a-descriptions-item>

          <a-descriptions-item label="创建者">
            <div class="creator-simple">
              <a-avatar :src="app.user?.userAvatar" :size="20">
                {{ app.user?.userName?.charAt(0) }}
              </a-avatar>
              <span>{{ app.user?.userName || '未知用户' }}</span>
            </div>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 初始提示词 -->
        <div class="prompt-section">
          <h3 class="section-title">初始提示词</h3>
          <div class="prompt-content">
            <a-textarea 
              :value="app.initPrompt" 
              :rows="6"
              readonly
              :placeholder="app.initPrompt ? undefined : '暂无初始提示词'"
              class="prompt-textarea"
            />
          </div>
        </div>

        <!-- 操作区域 -->
        <div class="action-section">
          <a-space size="large">
            <a-button 
              type="primary" 
              size="large" 
              @click="enterChat"
              :disabled="!app.id"
            >
              <template #icon><PlayCircleOutlined /></template>
              开始使用
            </a-button>

            <a-button 
              size="large" 
              @click="previewApp"
              :disabled="!app.id"
            >
              <template #icon><EyeOutlined /></template>
              预览效果
            </a-button>

            <a-button 
              v-if="app.deployKey"
              size="large" 
              @click="viewWork"
              :disabled="!app.deployKey"
            >
              <template #icon><GlobalOutlined /></template>
              查看作品
            </a-button>

            <a-button 
              v-if="canEdit()" 
              size="large" 
              @click="editApp"
              :disabled="!app.id"
            >
              <template #icon><EditOutlined /></template>
              编辑应用
            </a-button>
          </a-space>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state">
        <a-empty
          description="应用信息加载失败"
        >
          <template #image>
            <PlayCircleOutlined style="font-size: 64px; color: #d9d9d9" />
          </template>
          <a-button type="primary" @click="fetchAppDetail">重新加载</a-button>
        </a-empty>
      </div>
    </a-card>
  </div>
</template>

<style scoped>
.app-detail-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.detail-card {
  box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16),
              0 3px 6px 0 rgba(0, 0, 0, 0.12),
              0 5px 12px 4px rgba(0, 0, 0, 0.09);
  border-radius: 8px;
}

/* 页面头部 */
.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-button {
  padding: 0;
  color: #1890ff;
}

.back-button:hover {
  background: rgba(24, 144, 255, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

/* 应用信息 */
.app-info {
  margin-top: 24px;
}

.basic-info {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;
}

/* 应用封面 */
.app-cover {
  flex-shrink: 0;
  width: 200px;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e8e8e8;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-icon {
  font-size: 48px;
  color: #d9d9d9;
}

/* 应用元信息 */
.app-meta {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.app-title {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
  color: #262626;
  line-height: 1.2;
}

.meta-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.type-tag, .featured-tag, .deploy-tag {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 16px;
}

/* 创建者信息 */
.creator-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.creator-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.creator-name {
  font-size: 16px;
  font-weight: 500;
  color: #262626;
}

.creator-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #8c8c8c;
}

.creator-simple {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 提示词区域 */
.prompt-section {
  margin: 32px 0;
}

.section-title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.prompt-content {
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
}

.prompt-textarea {
  background: transparent;
  border: none;
  box-shadow: none;
}

:deep(.prompt-textarea .ant-input) {
  background: transparent;
  border: none;
  box-shadow: none;
  padding: 0;
  resize: none;
}

:deep(.prompt-textarea .ant-input:focus) {
  border: none;
  box-shadow: none;
}

/* 操作区域 */
.action-section {
  margin-top: 32px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  text-align: center;
}

/* 空状态样式 */
.empty-state {
  padding: 80px 20px;
  text-align: center;
}

.empty-state :deep(.ant-empty-description) {
  color: #8c8c8c;
  font-size: 16px;
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-detail-page {
    margin: 0;
  }

  .basic-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .app-cover {
    width: 100%;
    max-width: 300px;
  }

  .app-title {
    font-size: 24px;
  }

  .creator-info {
    justify-content: center;
  }

  :deep(.ant-descriptions) {
    font-size: 14px;
  }

  :deep(.ant-descriptions-item-label) {
    width: 80px;
  }

  .action-section {
    padding: 16px;
  }

  .action-section .ant-space {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
